package mwa.cs.rc.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.CustomerDAO;
import mwa.cs.dao.RcTransMDAO;
import mwa.cs.database.Database;
import mwa.cs.util.JDate;

/**
 * Servlet implementation class CS55002Srvl
 */
public class CS55002Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS55002Srvl() {
        super();
        // TODO Auto-generated constructor stub
    }
    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
    	vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		if (request.getParameter("process_type").equals("getDataTable")) {
			getDataTable(request, response);
		}
		
    }
    @SuppressWarnings("unchecked")
	public void getDataTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String vaStartDate = request.getParameter("sSearch_0").trim();
		String vaEndDate = request.getParameter("sSearch_1").trim();
		String vaAccount = request.getParameter("sSearch_2").trim();
		String vaStatus = request.getParameter("sSearch_3").trim();
		boolean vbSearch = false;
		if((!request.getParameter("sSearch_0").equals("")&&!request.getParameter("sSearch_1").equals(""))||!request.getParameter("sSearch_2").equals("")){
			 vbSearch = true;
		}
		if(vbSearch==false){
			vaStartDate ="-1";
			vaEndDate ="-1";
			vaAccount ="-1";
		}else{
			vaStartDate =JDate.saveDate(vaStartDate);
			vaEndDate =JDate.saveDate(vaEndDate);
		}
		
		String[] vaColumnsASC = { "receive_date ASC , receive_time ASC", "serial_number ASC", 
				"receive_date ASC , receive_time ASC","account ASC","name ASC","gross_amount ASC" };
		String[] vaColumnsDESC = { "receive_date DESC , receive_time DESC", "serial_number DESC", 
				"receive_date DESC , receive_time DESC","account DESC", "name DESC","gross_amount DESC" };
		
		String vaSortColumn = null;
		int vnStart = Integer.parseInt(request
				.getParameter("iDisplayStart")); // 0
		int vnAmount = Integer.parseInt(request
				.getParameter("iDisplayLength")); // 10
		int vnSortColumn = Integer.parseInt(request
				.getParameter("iSortCol_0")); // 0, 1, 2, 3
		String vaSortDirection = request.getParameter("sSortDir_0"); 
		
		if(vaSortDirection.equals("asc")){
			vaSortColumn = vaColumnsASC[vnSortColumn];
		}
		if(vaSortDirection.equals("desc")){
			vaSortColumn = vaColumnsDESC[vnSortColumn];
		}
		
		Database db = new Database();
		RcTransMDAO voRcTransMDAO = new RcTransMDAO(db);
		PrintWriter voOut = response.getWriter();
		List<Map<String, Object>> voList = new ArrayList<Map<String, Object>>();
		Map<String, Object> voMap = new HashMap<String, Object>();
		
		int pnEnd = vnStart + vnAmount;
		
		int vnTotalRecords = voRcTransMDAO.getCountAllRcTransMByBetweenDateAndAccount(vnSiteId, vaStartDate, vaEndDate, vaAccount, vaStatus, vaSortColumn);
		int vnTotalDisplayRecords = 0;
		if(vnAmount== -1){
			voList = voRcTransMDAO.findAllRcTransMByBetweenDateAndAccount(vnSiteId, vaStartDate, vaEndDate, vaAccount, vaStatus, vaSortColumn);
			vnTotalDisplayRecords = vnTotalRecords;
		}else{
			voList = voRcTransMDAO.findRcTransMByBetweenDateAndAccount(vnSiteId, vaStartDate, vaEndDate, vaAccount, vaStatus, vaSortColumn, vnStart, pnEnd);
			vnTotalDisplayRecords = voRcTransMDAO.getCountRcTransMByBetweenDateAndAccount(vnSiteId, vaStartDate, vaEndDate, vaAccount, vaStatus, vaSortColumn, vnStart, pnEnd);
		}
		
		JSONObject voObject = new JSONObject();
		JSONArray voListData = new JSONArray();
		JSONArray voArray = new JSONArray();
		String vaAccount2 = "";
		String vaName = "";
		CustomerDAO voCustomerDAO = new CustomerDAO(db);
		if(voList.size() != 0){
			
			for (int i = 0; i < voList.size(); i++) {
				voArray = new JSONArray();
				voMap = voList.get(i);
				voArray.add((i+1));
				if(voMap.get("SERIAL_NUMBER")!=null){
					voArray.add(voMap.get("SERIAL_NUMBER").toString());	
				}else{
					voArray.add("");	
				}
				if(voMap.get("RECEIVE_DATE")!=null&&voMap.get("RECEIVE_TIME")!=null){
					voArray.add(JDate.showDate(voMap.get("RECEIVE_DATE").toString())+" "+JDate.showTime(voMap.get("RECEIVE_TIME").toString()));
				}else{
					voArray.add("");
				}
				vaAccount = voMap.get("ACCOUNT").toString();
				
					if(voCustomerDAO.getCustomer(vnSiteId,vaAccount).get("ACCOUNT") == null){
						vaAccount2 = "";
					}else{
						vaAccount2 = (String) voCustomerDAO.getCustomer(vnSiteId,vaAccount).get("ACCOUNT");	
					}
					voArray.add(vaAccount2);
					if(voCustomerDAO.getCustomer(vnSiteId,vaAccount).get("NAME") == null){
						vaName = "";
					}else{
						vaName = (String) voCustomerDAO.getCustomer(vnSiteId,vaAccount).get("NAME");
					} 
				voArray.add(vaName);
				voArray.add(voMap.get("GROSS_AMOUNT").toString());
				if(voMap.get("STATUS")==null){
					voArray.add("รับเงิน");	
				}else{
					voArray.add("ยกเลิก");	
				}
				
				if(voMap.get("SERIAL_NUMBER")!=null){
					voArray.add(voMap.get("SERIAL_NUMBER").toString());	
				}else{
					voArray.add("");	
				}
				
				voListData.add(voArray);
			}
		}
		
		
		voObject.put("iTotalRecords", vnTotalRecords);
		voObject.put("iTotalDisplayRecords", vnTotalDisplayRecords);
		voObject.put("aaData", voListData);
		voObject.put("account", vaAccount2);
		voObject.put("name", vaName);
		
		db.close();
		voOut.print(voObject.toJSONString());
		
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
